import React, { useRef } from 'react';
import { ProTable, ActionType, ProColumns } from '@ant-design/pro-components';
import { message, Button } from 'antd';
import { RedoOutlined, ExceptionOutlined } from '@ant-design/icons';
import { downloadFile, proTableRequest, saveDataParams } from '@/app/common/utils';

import CreateForm from './CreateForm';

export type ConfigType = {
  configId: number;
  configName: string;
  configKey: string;
  configValue: string;
  configType: string;
  createBy: string;
};

const columns: ProColumns<ConfigType>[] = [
  {
    title: 'id',
    dataIndex: 'configId',
    width: 48,
    search: false,
    editable: false,
  },
  {
    title: '参数名称',
    dataIndex: 'configName',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
    search: false,
  },
  {
    title: '是否内置',
    dataIndex: 'configType',
    width: 90,
    valueType: 'select',
    valueEnum: {
      Y: {
        text: '是',
        status: 'Success',
      },
      N: {
        text: '否',
        status: 'Processing',
      },
    },
  },
  {
    title: '参数健名',
    dataIndex: 'configKey',
    valueType: 'text',
  },
  {
    title: '参数键值',
    dataIndex: 'configValue',
  },
  {
    title: '创建人',
    width: 90,
    dataIndex: 'createBy',
    valueType: 'text',
    editable: false,
    search: false,
  },
  {
    title: '备注',
    dataIndex: 'remark',
    valueType: 'text',
    ellipsis: true,
    search: false,
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    valueType: 'dateTime',
    sorter: true,
    hideInSearch: true,
    editable: false,
  },
  {
    title: '更新时间',
    key: 'updateTime',
    dataIndex: 'updateTime',
    valueType: 'dateTime',
    sorter: true,
    hideInSearch: true,
    editable: false,
  },
  {
    title: '操作',
    valueType: 'option',
    key: 'option',
    width: 80,
    render: (_text, record, _, action) => {
      return [
        <a
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.configId);
          }}
        >
          编辑
        </a>,
      ];
    },
  },
];

// 系统参数页面
export default function Config() {
  const actionRef = useRef<ActionType>();

  // 刷新缓存
  const refresh = async () => {
    const res = await $delete('/system/config/refreshCache');
    if (res.code === 200) {
      message.success('刷新缓存成功');
    }
  };

  return (
    <>
      <ProTable<ConfigType>
        columns={columns}
        actionRef={actionRef}
        request={proTableRequest('/system/config/list')}
        editable={{
          type: 'multiple',
          onSave: async function(_key, record) {
            const res = await $put('/system/config', { data: { ...saveDataParams(record) } });
            if (res.code === 200) {
              message.success('修改成功');
            }
            actionRef.current.reload();
          },
          onDelete: async function(_key) {
            const res = await $delete(`/system/config/${_key}`);
            if (res.code === 200) {
              message.success('删除成功');
            }
          },
        }}
        rowKey="configId"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 800,
          },
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 10,
        }}
        dateFormatter="string"
        headerTitle="系统参数"
        toolBarRender={action => [
          <CreateForm actionRef={action} />,
          <Button type="primary" icon={<RedoOutlined />} onClick={refresh}>
            刷新缓存
          </Button>,
          <Button
            type="primary"
            icon={<ExceptionOutlined />}
            onClick={async () => {
              const isSuccess = await downloadFile('/system/config/export');
              if (isSuccess) {
                message.success('下载成功');
              }
            }}
          >
            导出配置
          </Button>,
        ]}
      />
    </>
  );
}
